package com.edmendst.xmall.config;

import com.edmendst.xmall.filter.JwtAuthenticationFilter;
import com.edmendst.xmall.util.JWTUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig {


    private final JWTUtil jwtUtil;

    // 注入 JWTUtil
    public SecurityConfig(JWTUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
        System.out.println("SecurityConfig初始化时secret状态: " +
                (jwtUtil.getSecret() != null ? "已注入" : "未注入"));
    }

    /**
     * 显式定义 JwtAuthenticationFilter
     */
    @Bean
    public JwtAuthenticationFilter jwtAuthenticationFilter() {
        return new JwtAuthenticationFilter(jwtUtil); // 直接使用注入的 jwtUtil
    }


    /**
     * 配置Spring Security核心过滤器链，定义应用安全策略
     *
     * @param http HttpSecurity对象用于构建安全配置
     * @return 完整配置的安全过滤器链
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http

                // 禁用CSRF保护
                .csrf(csrf -> csrf.disable())
                // 启用默认CORS配置
                .cors(Customizer.withDefaults())

                // 请求授权规则配置
                // 开放登录页和静态资源，其余请求需要认证
                .authorizeHttpRequests(auth -> auth
                                // GET公开接口
                                .requestMatchers(HttpMethod.GET,
                                        "/product",
                                        "/product/{id}",
                                        "/product/keyword/**",
                                        "/product/category",
                                        "/product/category/{categoryId}",
                                        "/product_images/**",
                                        "/user_images/**",
                                        "/shop_images/**"
                                ).permitAll()

                                // 静态资源
                                .requestMatchers("/static/**", "/favicon.ico").permitAll()

                                .requestMatchers("/icon.png").permitAll() // 允许访问图标

                                .requestMatchers(HttpMethod.POST, "/pay/callback").permitAll()

                                .requestMatchers(HttpMethod.OPTIONS).permitAll()


                                // 认证相关POST接口
                                .requestMatchers(HttpMethod.POST,
                                        "/user",
                                        "/user/session",
                                        "/admin",
                                        "/admin/session"
                                ).permitAll()

                                .requestMatchers("/alipay/**").permitAll() //  忽略alipay接口的配置

                                // 需要认证的接口
                                .requestMatchers(
                                        "/user/**",
                                        "/cart/**",
                                        "/orders/**",
                                        "/recommendations",
                                        "/product/**",
                                        "/order/**",
                                        "/pay/**",
                                        "/shop/**",
                                        "/review/**"
                                ).authenticated() // 仅要求认证，不检查具体角色

                                .requestMatchers("/error").permitAll() // 防止错误页面触发403


//                                 管理员接口
//                        .requestMatchers(HttpMethod.PUT,
//                                "/product/category"
//                        ).hasRole("ADMIN")

                                // 其他请求策略
                                   .anyRequest().denyAll()  // 其他接口拒绝访问
//                                .anyRequest().permitAll()  //允许所有请求
                )

                // SecurityConfig.java 添加JWT过滤器
                .addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)

                .sessionManagement(session -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS));


        return http.build();
    }

}
